package com.lzb.yabbs.net;

import com.alibaba.fastjson.JSONObject;
import com.lzb.yabbs.dao.UserInfo;
import com.lzb.yabbs.interfaces.LoginCallback;
import com.squareup.okhttp.Callback;
import com.squareup.okhttp.Request;
import com.squareup.okhttp.Response;

import org.apache.http.message.BasicNameValuePair;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by liuzaibing on 2015/9/8.
 */
public class LoginToNet {

    public static final int LOGIN_PSD_USERNAME_ERRO=0x189;
    public static final int LOGIN_UNKOWN_ERROR=0x1234;

    public static void login(final String url, final LoginCallback loginCallback,String username,String psd){
        List<BasicNameValuePair> pairs=new ArrayList<>();
        BasicNameValuePair pair=new BasicNameValuePair("user",username);
        BasicNameValuePair pair1=new BasicNameValuePair("password",psd);
        pairs.add(pair);
        pairs.add(pair1);
        OkHttpClientRequest.requestGet(url, pairs, new Callback() {
            @Override
            public void onFailure(Request request, IOException e) {

            }

            @Override
            public void onResponse(Response response) throws IOException {
                String resultStr=response.body().string();
                JSONObject obj=JSONObject.parseObject(resultStr);
                if(0==obj.getInteger("code")){
                    loginCallback.loginFail(LOGIN_PSD_USERNAME_ERRO);
                }if(1==obj.getInteger("code")){
                    UserInfo userInfo=JSONObject.parseObject(resultStr,UserInfo.class);
                    if(userInfo!=null)
                        loginCallback.loginSuccess(userInfo);
                    else
                        loginCallback.loginFail(LOGIN_UNKOWN_ERROR);
                }else{
                    loginCallback.loginFail(LOGIN_UNKOWN_ERROR);
                }
            }
        });
    }
}
